import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import compression from 'compression';
import rateLimit from 'express-rate-limit';
import xss from 'xss-clean';
import dotenv from 'dotenv';
import { performanceMonitor, correctionPerformanceMonitor } from './middlewares/monitor.js';

// 加载环境变量
dotenv.config();

const app = express();

// ==================== 安全中间件 ====================

// Helmet - 设置安全HTTP头
app.use(helmet());

// CORS - 跨域资源共享
// 开发环境允许所有来源，生产环境只允许配置的域名
const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV === 'development';

const corsOptions = {
  origin: function (origin, callback) {
    // 开发环境：允许所有来源（包括无origin的请求如Postman）
    if (isDevelopment) {
      callback(null, true);
      return;
    }
    
    // 生产环境：检查白名单
    const allowedOrigins = process.env.CORS_ORIGIN 
      ? process.env.CORS_ORIGIN.split(',').map(o => o.trim())
      : [];
    
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      console.warn(`[CORS] Blocked request from origin: ${origin}`);
      callback(new Error('CORS策略不允许该来源的请求'));
    }
  },
  credentials: true,
  optionsSuccessStatus: 200,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
};

app.use(cors(corsOptions));

// 开发环境日志
if (isDevelopment) {
  console.log('[CORS] 开发环境模式：允许所有来源的请求');
}

// 速率限制
const limiter = rateLimit({
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15分钟
  max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100, // 限制100次请求
  message: '请求过于频繁，请稍后再试',
  standardHeaders: true,
  legacyHeaders: false,
});
app.use('/api/', limiter);

// XSS防护 - 清理用户输入
app.use(xss());

// ==================== 基础中间件 ====================

// HTTP请求日志
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
} else {
  app.use(morgan('combined'));
}

// 请求体解析
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 响应压缩
app.use(compression());

// ==================== 性能监控 ====================

// 应用性能监控中间件（记录所有API请求）
app.use(performanceMonitor);

// ==================== 路由 ====================

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'success',
    message: 'Server is running',
    timestamp: new Date().toISOString(),
    environment: process.env.NODE_ENV,
  });
});

// API根路径
app.get('/api', (req, res) => {
  res.status(200).json({
    message: 'AI Essay Correction API',
    version: '1.0.0',
    endpoints: {
      users: '/api/users',
      essays: '/api/essays',
      corrections: '/api/corrections',
      upload: '/api/upload',
    },
  });
});

// 导入路由模块
import userRoutes from './routes/userRoutes.js';
import essayRoutes from './routes/essayRoutes.js';
import uploadRoutes from './routes/uploadRoutes.js';
import correctionRoutes from './routes/correctionRoutes.js';

// 注册路由
app.use('/api/v1/users', userRoutes);
app.use('/api/v1/essays', essayRoutes);
app.use('/api/v1/upload', uploadRoutes);
app.use('/api/v1/corrections', correctionRoutes);

// ==================== 错误处理 ====================

// 404处理
app.use((req, res, next) => {
  res.status(404).json({
    code: 404,
    error: {
      type: 'NOT_FOUND',
      message: `无法找到路径: ${req.originalUrl}`,
    },
  });
});

// 全局错误处理中间件
app.use((err, req, res, next) => {
  // 记录错误日志
  console.error('Error:', {
    type: err.type || err.name,
    message: err.message,
    statusCode: err.statusCode,
    stack: err.stack,
  });

  // 确定HTTP状态码
  const statusCode = err.statusCode || 500;

  // 构建错误响应
  const response = {
    success: false,
    error: {
      type: err.type || err.name || 'SERVER_ERROR',
      message: err.message || '服务器内部错误',
    },
  };

  // 开发环境返回错误堆栈
  if (process.env.NODE_ENV === 'development' && err.stack) {
    response.error.stack = err.stack;
  }

  res.status(statusCode).json(response);
});

export default app;

